package com.puhui.lib.permission

import android.Manifest
import android.annotation.TargetApi
import android.app.Activity
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.PermissionUtils
import com.puhui.lib.BuildConfig
import com.puhui.lib.R
import com.puhui.lib.utils.AlertDialogUtils
import com.tbruyelle.rxpermissions2.Permission
import com.tbruyelle.rxpermissions2.RxPermissions
import com.trello.rxlifecycle3.android.ActivityEvent
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity
import io.reactivex.Observable
import io.reactivex.functions.Consumer
import java.lang.ref.WeakReference

object PermissionUtils {

    /**
     * 检测所需要的权限
     */
    fun checkNeededPermission(
        activity: FragmentActivity,
        permissions: Array<String>,
        callBack: CheckPermissionsCallBack
    ) {
        if (activity.isFinishing || activity.isDestroyed || activity.lifecycle.currentState == Lifecycle.State.DESTROYED) {
            return
        }

        if (permissions.size > 5) return

        var combined: Observable<Permission>? = null
        when (permissions.size) {
            1 -> combined = RxPermissions(activity).requestEachCombined(permissions[0])
            2 -> combined = RxPermissions(activity).requestEachCombined(permissions[0], permissions[1])
            3 -> combined = RxPermissions(activity).requestEachCombined(permissions[0], permissions[1], permissions[2])
            4 -> combined =
                RxPermissions(activity).requestEachCombined(
                    permissions[0],
                    permissions[1],
                    permissions[2],
                    permissions[3]
                )
            5 -> combined = RxPermissions(activity).requestEachCombined(
                permissions[0],
                permissions[1],
                permissions[2],
                permissions[3],
                permissions[4]
            )
            else -> if (BuildConfig.DEBUG) throw IllegalArgumentException("同时申请的权限不能多于5个")
        }

        if (activity is RxAppCompatActivity) {
            combined = combined?.compose(activity.bindUntilEvent(ActivityEvent.DESTROY))
        }

        val subscribe = combined?.subscribe(object : Consumer<Permission> {
            override fun accept(permission: Permission?) {
                permission?.let {
                    when {
                        it.granted -> callBack.onGenerated()
                        it.shouldShowRequestPermissionRationale -> callBack.onRefuse()
                        else -> callBack.onRefuseNotAsk()
                    }
                }
            }
        })
    }

    interface CheckPermissionsCallBack {
        fun onGenerated()

        fun onRefuse() {}

        fun onRefuseNotAsk() {}
    }

    private var mActivity: WeakReference<Activity>? = null
    private var alertDialog: AlertDialog? = null

    /**
     * 判断授权拒绝提示弹窗是否可见
     */
    fun isPermissionDialogShow(): Boolean {
        return alertDialog?.isShowing == true
    }

    /**
     * 隐藏权限被拒绝的提示弹窗
     */
    fun dismissAlertDialog(activity: Activity) {
        //判断当前Activity是否和上次的Activity相同，若相同，且Dialog处于显示状态才可操作dismiss()
        if (mActivity?.get() == activity && alertDialog?.isShowing == true) {
            alertDialog?.dismiss()
        }
    }

    /**
     * 请求权限被拒绝提示弹窗
     * @see isMust 用来控制弹窗是否可消失
     */
    fun showMissingPermissionDialog(
        activity: Activity, isMust: Boolean = true, tipTitle: String = "温馨提示",
        permissionDes: String = activity.getString(R.string.permission_common_msg),
        isTipContentHtml: Boolean = false
    ) {

        //判断当前Activity是否和上次的Activity相同，若相同，且Dialog处于显示状态，则不重新弹出
        if (mActivity?.get() == activity && alertDialog?.isShowing == true) {
            return
        }

        mActivity = WeakReference(activity)

        alertDialog = AlertDialogUtils.Builder.newInstance()
            .setCanCancelable(false)
            .setTitle(tipTitle)
            .setTipContent(permissionDes)
            .setCenter(false)
            .isContentHtml(isTipContentHtml)
            .setConfirmStr(activity.getString(R.string.go_setting))
            .setCancelStr(activity.getString(R.string.cancel))
            .setOnConfirmListener(object : AlertDialogUtils.OnConfirmListener {
                override fun onConfirm() {
                    PermissionUtils.launchAppDetailsSettings()
                }
            })
            .setOnCancelListener(object : AlertDialogUtils.OnCancelListener {
                override fun onCancel() {
                    if (!activity.isFinishing && !activity.isDestroyed && isMust) {
                        ActivityUtils.finishActivity(activity)
                    }
                }
            })
            .show(activity)
    }

//        val onClickListener = DialogInterface.OnClickListener { dialog, which ->
//            when (which) {
//                DialogInterface.BUTTON_NEGATIVE -> {
//                    dialog.dismiss()
//                    if (!activity.isFinishing && !activity.isDestroyed && isMust) {
//                        ActivityUtils.finishActivity(activity)
//                    }
//                }
//                DialogInterface.BUTTON_POSITIVE -> {
//                    if (!isMust) dialog.dismiss()
//                    PermissionUtils.launchAppDetailsSettings()
//                }
//            }
//        }

//        alertDialog = AlertDialog.Builder(activity)
//            .setTitle(context.getString(R.string.warm_prompt))
//            .setMessage(permissionDes)
//            .setNegativeButton(R.string.cancel, onClickListener)
//            .setPositiveButton(R.string.setting, onClickListener)
//            .setCancelable(false)
//            .create()
//        alertDialog?.show()

}

/**
 * APP可能所需要的权限
 */
object Permissions {
    //读取存储权限
    @JvmStatic
    val READ_WRITE_PERMISSION =
        arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)

    //电话权限
    @JvmStatic
    val PHONE_PERMISSION = arrayOf(Manifest.permission.READ_PHONE_STATE)

    //读取存储权限、电话权限
    @JvmStatic
    val READ_WRITE_PHONE_PERMISSION = arrayOf(
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )

    //定位权限
    @JvmStatic
    val LOCATION_PERMISSION =
        arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)

    //允许安装应用权限
    @JvmStatic
    @TargetApi(26)
    val INSTALL_PACKAGES_PERMISSION = arrayOf(Manifest.permission.REQUEST_INSTALL_PACKAGES)

    //拍照权限 一般都伴随着存储权限
    @JvmStatic
    val CAMERA_PERMISSION = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE
    )
}